import { setRightMenu } from './menu';
import getCellName from '../../../../utils/getCellName';
import { Tools,Toast } from 'weaver-mobile';
import { each } from 'lodash';
import { getFieldName,getcusFiledName, getcusFiledCurrentT, getpreBindingPath } from '../../../excel/action/common';

const { getLabel } = Tools;
export function dragFillBlock(e, info) {
    try{
      
    const { sheet, fillRange, fillDirection } = info;
    this.cantriggerClick = false;
    sheet.suspendPaint();
    const { row, col, colCount } = fillRange;
    const getDragCol = (table, colIndex, colSize) => {
        const dataRange = table.dataRange();
        const cols = [];
        const {row} = dataRange;
        for (let index = 0; index < colSize; index++) {
            const cell = sheet.getCell(row,colIndex + index);
            // 过滤掉只读字段
            if(cell.cellType() && cell.cellType().viewAttr != '1') {

                cols.push(table.getColumnDataField(colIndex + index - dataRange.col));
            }
        }
        return cols;
    }
    if (fillDirection === window.GC.Spread.Sheets.Fill.FillDirection.down) {
        const newRecords = [];
        const startCell = sheet.getCell(row-1, col);
        const table = sheet.tables.find(row - 1, col);
        if(startCell.cellType() && table && table.bindingPath()){
            const tableName = table.bindingPath();
            const records = this.dataSourceInstance.getValue(tableName);
            const dataRange = table.dataRange();
            const cols = getDragCol(table, col, colCount);
            const dragRecord = records[row - dataRange.row - 1];
            const copyRecord = {};
            cols.forEach(c => {
                copyRecord[c] = dragRecord[c];
            });
            let detailIndex = 1;
            for (let index = 0; index < dataRange.rowCount; index++) {
                const currentRow = dataRange.row + index;
                if (currentRow < row) {
                    newRecords.push({ ...records[index], detail_index: detailIndex++ });
                } else if (currentRow >= row) {
                    if (currentRow < fillRange.row + fillRange.rowCount) {
                        newRecords.push({ ...records[index], ...copyRecord, detail_index: detailIndex++ });
                    } else {
                        newRecords.push({ ...records[index], detail_index: detailIndex++ });
                    }
                }
            }
            const fillSize = fillRange.row + fillRange.rowCount;
            for (let index = dataRange.row + dataRange.rowCount; index < fillSize; index++) {
                newRecords.push({ ...copyRecord, detail_index: detailIndex++ });
            }

            this.dataSourceInstance.setValue(tableName, newRecords);
            table.bindingPath(tableName);
        }
    }
    this.calcAll(true, sheet.name());
    sheet.resumePaint();
    info.cancel = true;
    setTimeout(() => {
        this.cantriggerClick = true;
    }, 100);
      
} catch(e) {
    console.log(e)
    
}
}
export function ClipboardChanged(e, info) {
    const { sheet } = info;
    this.clipboardRanges = sheet.getSelections();
}
export function clipboardPasted(info) {
    const { sheetName, fromRanges = [], fromSheet, pastedRanges, clipboardText } = info;
    if (!this.readonly) {
        this.workbook.commandManager().execute({
            autoFitType: window.GC.Spread.Sheets.AutoFitType.cell,
            cmd: 'edc.excelView.paste',
            sheet: this.workbook.getSheetFromName(sheetName),
            sourceRange: fromRanges && fromRanges[0],
            sourceSheet: fromSheet,
            cellRange: pastedRanges && pastedRanges[0],
            value: clipboardText,
            callback: this.calcAll.bind(this, false, sheetName)
        });
    }
}

export function cellClick(e, data) {
    if (this.readonly) {
        return;
    }
    const { sheet, row, col } = data;
    const range = sheet.getCell(row, col);
    const cellType = range.cellType();
    if (cellType && cellType.viewAttr == 1) {
        return;
    }
    // if (cellType instanceof WeaDatePickerCellType) {
    //     const host = this.workbook.getHost();
    //     const offset = jQuery(host).offset();
    //     const rect = sheet.getCellRect(row, col);
    //     cellType.showDatePicker(rect.x + offset.left, rect.y + offset.top, range);
    // } else if (cellType instanceof WeaTimePickerCellType) {
    //     const host = this.workbook.getHost();
    //     const offset = jQuery(host).offset();
    //     const rect = sheet.getCellRect(row, col);
    //     cellType.showTimePicker(rect.x + offset.left, rect.y + offset.top, range);
    // }
}

export function enterCell(e, info) {
    const { sheet, row, col } = info;
    const table = sheet.tables.find(row, col);
    if (table) {
        // 只有可编辑时才可以添加行
        if (this.canSubmit) {
            const range = sheet.getCell(row, col);
            const cellType = range.cellType();
            setRightMenu(this, "1", row < table.dataRange().row, table, cellType, this.rowControl,sheet);
        } else {
            setRightMenu(this, "0");
        }
        this.activeCellName = `${getCellName(row, col)}(${table.name()})`;
    } else {
        setRightMenu(this, "0");
        this.activeCellName = getCellName(row, col);
    }
}

export function editStarting(e, info) {
    const { sheet, row, col } = info;
    const cellType = sheet.getCell(row, col).cellType();
    if (this.readonly) {
        info.cancel = true;
    } else if (cellType && cellType.viewAttr == 1) {
        info.cancel = true;
    } else {
        if (cellType instanceof window.WeaInputCellType || cellType instanceof window.WeaCheckboxCellType ||
            cellType instanceof window.WeaBrowserCellType || cellType instanceof window.WeaSelectCellType) {
        } else {
            info.cancel = true;
        }
    }
}

export function activeSheetChange(e, info) {
    this.workbook.suspendPaint();
    if (info.newSheet) {
        info.newSheet.setDataSource(this.dataSourceInstance);
        info.newSheet.tables.all().forEach((table, tableIndex) => {
            table.bindingPath(table.bindingPath())
        });
        if (info.newSheet.hasCalcAll) {
            this.calcAll(false, info.newSheet.name());
        } else {
            info.newSheet.hasCalcAll = true;
            this.calcAll(true, info.newSheet.name());
        }

    }
    this.workbook.resumePaint();
}

export function editEnded(e, info) {
    const { sheet, row, col, editingText } = info;

    const table = sheet.tables.find(row, col);
    if (table) {
        const { spanKeys } = table;
        const { col: startCol } = table.dataRange();
        if (spanKeys && spanKeys.length > 0) {
            spanKeys.forEach(key => {
                if (key.index + startCol === col) {
                    const span = sheet.getSpan(row, col);
                    if (span) {
                        sheet.getRange(span.row, span.col, span.rowCount, span.colCount).value(editingText);
                    }
                }
            });
        }
        //table.bindingPath(table.bindingPath());
        this.calcAll(false, sheet.name());
    }
}
const GetLength = (str) => {
    ///<summary>获得字符串实际长度，中文3，英文1</summary>
    ///<param name="str">要获得长度的字符串</param>
    var realLength = 0, len = str.length, charCode = -1;
    for (var i = 0; i < len; i++) {
        charCode = str.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128)
            realLength += 1;
        else
            realLength += 3;
    }
    return realLength;
};
const GetIndex = (str,length) => {
    let realLength = 0;
    let charCode = -1;
    for (var i = 0; i < str.length; i++) {
        charCode = str.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128){
            realLength += 1;
        }else{
            realLength += 3;
        }

        if(realLength===length){
            return i;
        }else if(realLength>length){
            return i-1;
        }

    }
}
export function cellChanged(e, info) {
    const { propertyName, newValue, oldValue, row, col, sheet,sheetArea } = info;
    if (propertyName === 'value' && this.needCheck) {
        const cell = sheet.getCell(row, col);
        const cellType = cell.cellType();
        if (cellType) {
            if (cellType instanceof window.WeaInputCellType) {
                const { fieldType: [htmlType, type, dbtype] } = cellType;
                if (type === 'text') {
                    if (newValue) {
                        const length = parseInt(dbtype);
                        if (GetLength(`${newValue}`) > length) {
                            if(GetLength(`${oldValue}`) > length){
                                const value = oldValue.substring(0,GetIndex(oldValue,length)+1);
                                cell.value(value);
                            }else{
                                cell.value(oldValue);
                            }
                            Toast.fail(`${getLabel('502997', '长度不能超过') + length}`);
                        }
                    }
                } else if (type === 'int') {
                    if (newValue) {

                        const realValue = parseInt(newValue);
                        if (isNaN(realValue)) {

                            Toast.fail(getLabel('502998', '请输入整数'));
                            cell.value(oldValue);
                        } else {
                            if ((newValue + '').replace("-",'').length >= 11) {
                                Toast.fail(getLabel('512017','整数最大长度为10位'));
                                cell.value(oldValue);
                                return;
                            }
                            if(realValue>2147483647||realValue<-2147483648){
                                Toast.fail(getLabel('512018','整数的范围为[-2147483648,2147483647]'));
                                cell.value(oldValue);
                                return;
                            }
                            cell.value(realValue);
                        }
                    }
                } else if (type === 'float') {
                    console.log("float",newValue);
                    if (newValue) {
                        const realValue = parseFloat(newValue);
                        const length = parseInt(dbtype);
                        if (isNaN(realValue)) {
                            Toast.fail(getLabel('502999', '请输入浮点数'));
                            cell.value(oldValue);
                        } else {
                            const value = toDecimal2(newValue,Number(dbtype));
                            if (value.length > 37) {
                                Toast.fail(getLabel('515704','浮点数最大长度为36位'));
                                cell.value(oldValue);
                                return;
                            }
                            cell.value(value);
                        }
                    }
                }
            } else if (cellType instanceof window.WeaPicCellType) {
                if(newValue){
                    const { showPic, imageWidth, imageHeight } = cellType;
                    showPic(newValue, { row: row, col: col, sheet: sheet, sheetArea: sheetArea });
                } 
             } else {
                if(this.isAssign) {
                    this.workbook.suspendPaint();
                    const table = sheet.tables.find(row, col);
                    const expandType = cellType.expandType;
                    // 自定义明细表纵向合并不全赋值
                    if (table && expandType!=2) {
                        const { spanKeys } = table;
                        const { col: startCol } = table.dataRange();
                        if (spanKeys && spanKeys.length > 0) {
                            spanKeys.forEach(key => {
                                if (key.index + startCol === col) {
                                    const span = sheet.getSpan(row, col);
                                    if (span) {
                                        sheet.getRange(span.row, span.col, span.rowCount, span.colCount).value(newValue);
                                    }
                                }
                            });
                        }
                        //table.bindingPath(table.bindingPath());
                        this.calcAll(false, sheet.name());
                    }
    
                    this.workbook.resumePaint();
                }
                
            }

            // 下拉框联动逻辑
            if (cellType instanceof window.WeaSelectCellType && newValue != '-999') {

                // 下拉框改变值判断，如果不存在，则不变化
                const items = cellType.items();

                let hasValue = false;
                if(items && items.length > 0 && newValue) {
                    items.forEach(b => {if(b.value == newValue) hasValue = true})
                }

                // 变更值存在
                if(hasValue || !newValue) {
                    if(typeof newValue === 'number') {
                        cell.value(newValue + '');
                        return;
                    }
                    const filedType = cellType.fieldType;
                    if (filedType && filedType[2]) {
                        const relatedChild = filedType[2].relatedChild;
                        const datas = filedType[2].datas;
    
    
                        if (relatedChild) {
                            // 下拉框选择的值
                            const selectValue = datas.filter(r => r.selectValue == newValue)[0];
                            // 选择框有值时
                            if (selectValue && newValue) {
    
                                relatedChildFun(relatedChild, selectValue.childValue, newValue, cellType, sheet, row, col);
                            } else {
                                relatedChildFun(relatedChild, undefined, undefined, cellType, sheet, row, col);
                            }
                        }
                    }
                } else {
                    cell.value(oldValue == '-999' || !oldValue ? '': oldValue );
                }
   
            }
                // 自定义明细表逻辑(扩展字段)
                const expandType = cellType.expandType;
                const table = sheet.tables.find(row, col);
                let needExpand = false;
                if(table && table.name().startsWith("custom")) {
                    const {row : tableRow, rowCount, col : tableCol, colCount} = table.dataRange();
                    const cellname = getcusFiledName(cell.bindingPath());
                    if(expandType == '2') {
                        let hasHandle = "@";
                        // 考虑合并单元格问题
                        const span = sheet.getSpan(row, col);
                        for(let c = col + 1; c < colCount + tableCol ; c++) {
                            if(span) {
                                const {row:spanRow ,rowCount:spanCount} = span;
                                // 合并单元格，所有行都需要一起变换
                                for(let r = spanRow; r<spanCount+ spanRow; r++) {
                                    const cCell = sheet.getCell(r, c);
                                    const cbindingPath = cCell.bindingPath();
                                    if(cbindingPath) {
                                        
                                        const preBindingPath = getpreBindingPath(cbindingPath);
                                        if(hasHandle.indexOf("@" + preBindingPath + "@" ) == -1) {
                                            //console.log(preBindingPath + cellname,"赋相同纵向扩展值")
                                            this.dataSourceInstance.setValue(preBindingPath + cellname, newValue);
                                            hasHandle = hasHandle + preBindingPath + "@";
                                        }
        
                                    }
                                }
                            } else {
                                const cCell = sheet.getCell(row, c);
                                const cbindingPath = cCell.bindingPath();
                                if(cbindingPath) {
                                    
                                    const preBindingPath = getpreBindingPath(cbindingPath);
                                    if(hasHandle.indexOf("@" + preBindingPath + "@" ) == -1) {
                                        //console.log(preBindingPath + cellname,"赋相同纵向扩展值")
                                        this.dataSourceInstance.setValue(preBindingPath + cellname, newValue);
                                        hasHandle = hasHandle + preBindingPath + "@";
                                    }
    
                                }
                            }
                            
                            
                        }
                    } else if(expandType == '1') {
                        const customBindingPath = sheet.name() + "." + table.name();
                        const rightExpandTypeList = this.otherrightExpandMap[customBindingPath];
                        if(rightExpandTypeList) {
                            for(let i = 0 ; i < rightExpandTypeList.length ; i++) {
                                const {fieldname} = rightExpandTypeList[i];
                                if(fieldname == cellname){
                                    needExpand = true;
                                }
                            }
                        }
                        
                        if(needExpand) {
                            let hasHandle = "@";
                            const span = sheet.getSpan(row,col);
                            for(let r = row + 1; r < tableRow + rowCount ; r++) {
                                if(span) {
                                    const{col:spanCol, colCount:spanColCount} = span;
                                    for(let c = spanCol; c<spanCol + spanColCount; c++) {
                                        const cCell = sheet.getCell(r, c);
                                        const cbindingPath = cCell.bindingPath();
                                        if(cbindingPath) {
                                            
                                            const preBindingPath = getpreBindingPath(cbindingPath);
                                            if(hasHandle.indexOf(preBindingPath) == -1) {
                                                //console.log(preBindingPath + cellname,"赋相同值")
                                                this.dataSourceInstance.setValue(preBindingPath + cellname, newValue);
                                                hasHandle = hasHandle + preBindingPath + "@";
                                            }
        
                                        }
                                    }
                                } else {
                                    const cCell = sheet.getCell(r, col);
                                    const cbindingPath = cCell.bindingPath();
                                    if(cbindingPath) {
                                        
                                        const preBindingPath = getpreBindingPath(cbindingPath);
                                        if(hasHandle.indexOf(preBindingPath) == -1) {
                                            //console.log(preBindingPath + cellname,"赋相同值")
                                            this.dataSourceInstance.setValue(preBindingPath + cellname, newValue);
                                            hasHandle = hasHandle + preBindingPath + "@";
                                        }
    
                                    }
                                }

                            }
                        }
                    }
                }
                
             
            if (this.isAssign) {
                let trigger = true;
                if (cellType instanceof window.WeaSelectCellType) {
                    // && oldValue!='-999'
                    if (newValue == '-999' || oldValue == '-999') {
                        trigger = false;
                    }
                }
                if (getFieldValue(newValue) === getFieldValue(oldValue)) {
                    trigger = false;
                }
                if (trigger) {
                    clearInterval(this.timer);//清除定时器
                    const table = sheet.tables.find(row, col);
                    let changeField = "";
                    let detailIndex = 0;
                    if (table) {
                        const dataRange = table.dataRange();
                        const mxColumn = table.getColumnDataField(col - dataRange.col);
                        detailIndex = row - dataRange.row + 1;//改变字段的明细表记录索引
                        const bindingPath = table.bindingPath();
                        changeField = bindingPath + "." + mxColumn;//字段名
                        this.changeFieldList.push({ changeField: changeField, detailIndex: detailIndex - 1 });
                    } else {
                        changeField = sheet.getCell(row, col).bindingPath();//改变字段是主表字段
                        this.changeFieldList.push({ changeField: changeField });
                    }
                    this.timer = setTimeout(this.getFieldAssignList, 1000, this.changeFieldList);//1s后执行函数
                }
            }
        }

        if (this.requiredCellName && this.requiredCellName == (row + "@" + col)) {
            if (cell.text()) {
                if (this.requiredCellBoderStyle[this.requiredCellName]) {

                    const requireSpan = sheet.getSpan(row,col);
                    if(!requireSpan) {
                        cell.setBorder(this.requiredCellBoderStyle[this.requiredCellName][0], { top: true });
                        cell.setBorder(this.requiredCellBoderStyle[this.requiredCellName][1], { right: true });
                        cell.setBorder(this.requiredCellBoderStyle[this.requiredCellName][2], { bottom: true });
                        cell.setBorder(this.requiredCellBoderStyle[this.requiredCellName][3], { left: true });
                    } else {
                        let index = 0;
                        for(let r = requireSpan.row; r < requireSpan.row + requireSpan.rowCount; r++) {
                            for(let c = requireSpan.col; c < requireSpan.col + requireSpan.colCount; c++) {
                                const requireCell = sheet.getCell(r, c);
                                requireCell.setBorder(this.requiredCellBoderStyle[this.requiredCellName][index][0], { top: true });
                                requireCell.setBorder(this.requiredCellBoderStyle[this.requiredCellName][index][1], { right: true });
                                requireCell.setBorder(this.requiredCellBoderStyle[this.requiredCellName][index][2], { bottom: true });
                                requireCell.setBorder(this.requiredCellBoderStyle[this.requiredCellName][index][3], { left: true });
                                index = index + 1;
                            }
                        }
                    }

                    
                }
                this.requiredCellName = "";
            }

            
        }

        if(this.autoFitSheetMap && this.autoFitSheetMap[sheet.name()]) {
            if(cellType instanceof window.WeaSelectCellType){
                if(newValue != '-999' && oldValue!='-999'){
                    setCurrentRowHeight(sheet, row,this.workbook)
                }
            }else if(cell.value() && !(cellType instanceof window.WeaPicCellType)){
                setCurrentRowHeight(sheet, row, this.workbook)
            }
        }

    }

   
}

function setCurrentRowHeight(sheet, row, workbook) {
    const oldHeight = sheet.getRowHeight(row);
    workbook.commandManager().autoFitRow.j4.canUndo = false
    sheet.autoFitRow(row);
    workbook.commandManager().autoFitRow.j4.canUndo = true
    const newHeight = sheet.getRowHeight(row);

    if(oldHeight > newHeight) {
        sheet.setRowHeight(row, oldHeight);
        //sheet.getCell(row,1).rowHeight  = 
    }
}

function relatedChildFun(relatedChild, childValues, value, cellType, sheet, row, cellcol) {

    const cvalues = childValues ? childValues.split(",") : undefined;
    const table = sheet.tables.find(row, cellcol);
    let bindingPath = "";
    let fieldName = "";
    let istable = 0;
    if (table && table.bindingPath()) {
        // 明细表
        const bindingPath = table.bindingPath();
        if (bindingPath) {
            const { col, colCount, rowCount } = table.dataRange();
            for (let i = 0; i < colCount; i++) {
                const childCell = sheet.getCell(Number(row), Number(col + i));
                const cellType = childCell.cellType();
                if (cellType && cellType.typeName == 'WeaSelectCellType' && cellType.fieldType) {
                    const fieldName = table.getColumnDataField(i);
                    if (relatedChild == fieldName) {
                        let newItems = [];
                        if (cvalues) {
                            newItems = cellType.fieldType[2].datas.filter(r =>
                                cvalues.indexOf(r.selectName) > -1
                            );
                        } else if (value) {
                        } else {
                            // 父字段没有值，子字段也不能选
                            //newItems = cellType.fieldType[2].datas;
                        }

                        if (newItems.length == 0 && childCell.value()) {
                            childCell.value(undefined);
                        } else {
                            if (newItems.filter(r => r.selectValue == childCell.value()).length < 1) {
                                if(childCell.value()) {
                                    childCell.value(undefined);
                                }
                            }
                        }
                        cellType.items(newItems.map((d) => ({ text: d.selectName, value: '' + d.selectValue })));

                    }
                }
            }
        }

    } else if(table && table.name().startsWith("custom")) {
        const expandType = cellType.expandType;
        
        const {row : tableRow,rowCount: rcount, col, colCount} = table.dataRange();
        // 纵向扩展
        if(expandType == '2') {

            let rowcount = 1;
            let startRow = row;
            // 纵向扩展的合并单元格
            const span = sheet.getSpan(row, cellcol);
            if(span) {
                rowcount = span.rowCount;
                startRow = span.row;
            }

            let targetRow;
            for(let c = col ; c < col + colCount; c++ ) {

                if(!targetRow) {

                    for(let r = 0; r < rowcount; r++) {
                        const childCell = sheet.getCell(startRow+r, c);
                        const cCelltype = childCell.cellType();
                        // 获取到关联的子下拉框
                        if(childCell.bindingPath() && cCelltype && cCelltype.typeName == 'WeaSelectCellType' 
                        && getcusFiledName(childCell.bindingPath()) == relatedChild) {
                            let newItems = [];
                            if (cvalues) {
                                newItems = cCelltype.fieldType[2].datas.filter(r =>
                                    cvalues.indexOf(r.selectName) > -1
                                );
                            } else if (value) {
                            } else {
                                // 父字段没有值，子字段也不能选
                                //newItems = cellType.fieldType[2].datas;
                            }
    
                            if (newItems.length == 0 && childCell.value()) {
                                childCell.value(undefined);
                            } else {
                                if (newItems.filter(r => r.selectValue == childCell.value()).length < 1) {
                                    if(childCell.value()) {
                                       childCell.value(undefined);
                                    }
                                }
                            }
                            cCelltype.items(newItems.map((d) => ({ text: d.selectName, value: '' + d.selectValue })));
                        }
                    }

                } else {

                    // 后期如果行数很多，可以考虑根据目标行来减少循环
                }
            }



        } else if(expandType == '1') {
            let colCount = 1;
            let startCol = cellcol;
            
            // 纵向扩展的合并单元格
            const span = sheet.getSpan(row, cellcol);
            if(span) {
                colCount = span.colCount;
                startCol = span.col;
            }
            // 横向扩展
            for(let r = tableRow; r < tableRow + rcount; r++) {
                for(let c = 0 ; c < colCount; c++) {
                    let colCol = startCol + c;
                    const childCell = sheet.getCell(r, colCol);
                    const cCelltype = childCell.cellType();
                    // 获取到关联的子下拉框
                    if(childCell.bindingPath() && cCelltype && cCelltype.typeName == 'WeaSelectCellType' 
                    && getcusFiledName(childCell.bindingPath()) == relatedChild) {
                        let newItems = [];
                        if (cvalues) {
                            newItems = cCelltype.fieldType[2].datas.filter(r =>
                                cvalues.indexOf(r.selectName) > -1
                            );
                        } else if (value) {
                        } else {
                            // 父字段没有值，子字段也不能选
                            //newItems = cellType.fieldType[2].datas;
                        }
                        if (newItems.length == 0 && childCell.value()) {
                            childCell.value(undefined);
                        } else {
                            if (newItems.filter(r => r.selectValue == childCell.value()).length < 1) {
                                if(childCell.value()) {
                                    childCell.value(undefined);
                                }
                            }
                        }
                        cCelltype.items(newItems.map((d) => ({ text: d.selectName, value: '' + d.selectValue })));
                    }
                }
                
            }
        } else {
            // 普通字段的联动
            let colCount = 1;
            let startCol = cellcol;
            
            const cell = sheet.getCell(row, cellcol);
            // 纵向扩展的合并单元格
            const span = sheet.getSpan(row, cellcol);
            if(span) {
                colCount = span.colCount;
                startCol = span.col;
            }
            // 横向扩展
            for(let r = tableRow; r < tableRow + rcount; r++) {
                for(let c = 0 ; c < colCount; c++) {
                    let colCol = startCol + c;
                    const childCell = sheet.getCell(r, colCol);
                    const cCelltype = childCell.cellType();
                    // 获取到关联的子下拉框
                    if(childCell.bindingPath() && cCelltype && cCelltype.typeName == 'WeaSelectCellType' 
                    && getcusFiledName(childCell.bindingPath()) == relatedChild && 
                    getpreBindingPath(childCell.bindingPath()) == getpreBindingPath(cell.bindingPath())) {
                        let newItems = [];
                        if (cvalues) {
                            newItems = cCelltype.fieldType[2].datas.filter(r =>
                                cvalues.indexOf(r.selectName) > -1
                            );
                        } else if (value) {
                        } else {
                            // 父字段没有值，子字段也不能选
                            //newItems = cellType.fieldType[2].datas;
                        }
                        if (newItems.length == 0 && childCell.value()) {
                            childCell.value(undefined);
                        } else {
                            if (newItems.filter(r => r.selectValue == childCell.value()).length < 1) {
                                if(childCell.value()) {
                                    childCell.value(undefined);
                                }
                            }
                        }
                        cCelltype.items(newItems.map((d) => ({ text: d.selectName, value: '' + d.selectValue })));
                    }
                }
                
            }
        }

    }else {
        const path = sheet.getBindingPath(row, cellcol);
        if (path) {

            //const [path, fieldName] = path.split('.');
            const { data } = sheet.toJSON();
            if (data) {
                const { dataTable } = data;
                if (dataTable) {
                    each(dataTable, (o, rowIndex) => {
                        each(o, (obj, colIndex) => {
                            const bindingPath = sheet.getBindingPath(rowIndex, colIndex);
                            if (bindingPath) {

                                const [sheetName, fieldName] = bindingPath.split('.');
                                if (relatedChild == fieldName) {
                                    const childCell = sheet.getCell(Number(rowIndex), Number(colIndex));
                                    const cellType = childCell.cellType();
                                    if (cellType && cellType.typeName == 'WeaSelectCellType' && cellType.fieldType) {

                                        let newItems = [];
                                        if (cvalues) {
                                            newItems = cellType.fieldType[2].datas.filter(r =>
                                                cvalues.indexOf(r.selectName) > -1
                                            );
                                        } else if (value) {
                                        } else {
                                            //newItems = cellType.fieldType[2].datas;
                                        }
                                        if (newItems.length == 0 && childCell.value()) {
                                            childCell.value(undefined);
                                        } else {
                                            if (newItems.filter(r => r.selectValue == childCell.value()).length < 1) {
                                                if(childCell.value()) {
                                                    childCell.value(undefined);
                                                }
                                            }
                                        }
                                        cellType.items(newItems.map((d) => ({ text: d.selectName, value: '' + d.selectValue })));
                                    }
                                }

                            }

                        });
                    });

                }
            }
        }
    }
} 

export function getFieldValue(value) {
    let returnValue = "";
    if (value && Array.isArray(value)) {
        let idArr = new Array();
        value.forEach((o) => {
            idArr.push(o.id);
        });
        returnValue = idArr.join(",");
    } else {
        returnValue = value;
    }
    return String(returnValue);
}

//强制保留num位小数，如：2，会在2后面补上00.即2.00 
export function toDecimal2(s,num) {
    let pre = ""
    if (s.indexOf("-") == 0) {
        pre = "-"
    }
    s = s.replace(/[^\d\.]/g, "");
    let rs = s.indexOf('.');

    if(rs > -1) {
        let rightstr = s.substring(rs+1);
        let leftstr = s.substring(0,rs+1);
        const Re = new RegExp("\\.","g");
        rightstr = rightstr.replace(Re,"");
        leftstr = leftstr.replace(/\b(0+)/gi,"");
        s = leftstr + rightstr;
    }
    
    rs = s.indexOf('.');
    if(rs == 0) {
        s = "0" + s;
        rs = rs + 1;
    }
    if (rs < 0) {
        rs = s.length;
        s += '.00';
    } else if (s.length > rs + num) {
        s = s.substring(0, rs + num+1)
    }

    while (s.length <= rs + num) {
        s += '0';
    }
    return pre + s;
}

export function rangeChanged(e, info) {
    
    //获取改变的单元格
    const { changedCells, sheet } = info;
    changedCells.map((o) => {
        const { row, col } = o;
        const cell = sheet.getCell(Number(row), Number(col));
        const fu = sheet.getCell(row, col).formula();

        const cellType = sheet.getCell(row, col).cellType();

        const newValue = sheet.getCell(row, col).value();

        if (fu) {

            if (cellType && cellType.typeName == 'WeaSelectCellType' && newValue && newValue != '-999') {
                const filedType = cellType.fieldType;
                if (filedType && filedType[2]) {
                    const relatedChild = filedType[2].relatedChild;
                    const datas = filedType[2].datas;
                    // 下拉框改变值判断，如果不存在，则不变化
                    const items = cellType.items();

                    let hasValue = false;
                    if(items && items.length > 0) {
                        items.forEach(b => {if(b.value === newValue) hasValue = true})
                    }
                    console.log(hasValue, newValue,items);
                    // 变更值存在
                    if(hasValue) {
                    if (relatedChild) {
                        // 下拉框选择的值
                        const selectValue = datas.filter(r => r.selectValue == newValue)[0];
                        // 选择框有值时
                        if (selectValue && newValue) {

                            relatedChildFun(relatedChild, selectValue.childValue, newValue, cellType, sheet, row, col);
                        } else {
                            relatedChildFun(relatedChild, undefined, undefined, cellType, sheet, row, col);
                        }
                    }
                } 
                else if(newValue){
                    
                cell.formula(undefined);
                    cell.value('');
                    
                    return;
                }
                }

            }

            const table = sheet.tables.find(row, col);
            let changeField = "";
            let detailIndex = 0;
            if (table) {
                const dataRange = table.dataRange();
                const mxColumn = table.getColumnDataField(col - dataRange.col);
                detailIndex = row - dataRange.row + 1;//改变字段的明细表记录索引
                const bindingPath = table.bindingPath();
                changeField = bindingPath + "." + mxColumn;//字段名
                this.changeFieldList.push({ changeField: changeField, detailIndex: detailIndex - 1 });
            } else {
                changeField = sheet.getCell(row, col).bindingPath();//改变字段是主表字段
                this.changeFieldList.push({ changeField: changeField });
            }
        }
    });
}
